package com.simple.orm.agreement.process.impl;

import com.simple.orm.agreement.annotation.Order;
import com.simple.orm.agreement.process.AbstractReadProcess;
import com.simple.orm.agreement.utils.DataInputStreamUtil;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class DefaultReadProcess<T> extends AbstractReadProcess<T> {

    @Override
    protected T parse(Class<?> aClass) {
        Field[] fields = aClass.getDeclaredFields();
        List<Field> list = new ArrayList<>();
        for (Field field : fields) {
            Order order = field.getDeclaredAnnotation(Order.class);
            if (order == null) continue;
            list.add(field);
        }
        list.sort((o1, o2) -> {
            Order order1 = o1.getDeclaredAnnotation(Order.class);
            Order order2 = o2.getDeclaredAnnotation(Order.class);
            return order1.value() - order2.value();
        });
        T t = instance((Class<T>) aClass);
        list.forEach(field -> {
            boolean accessible = field.isAccessible();
            field.setAccessible(true);
            try {
                field.set(t, DataInputStreamUtil.readData(dataInputStream, field));
            } catch (IllegalAccessException | IOException e) {
                e.printStackTrace();
            } finally {
                field.setAccessible(accessible);
            }
        });
        return t;
    }
}
